package com.chat.http.intercepter;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.chat.util.ResponseUtil;
import com.chat.websocket.online.OnlineManage;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 访问前在线过滤
 * 
 * @author lwh
 *
 */
public class PrivilegeInterceptor extends HandlerInterceptorAdapter {
	
	private static final Logger logger = Logger.getLogger(PrivilegeInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		String uri = request.getRequestURL().toString();
		logger.info("-------------->> 访问 URI： " + uri);
		//Data服务器请求添加预备连接用户，放行
		if( uri.contains( "/planConn" ) ){
			return true;
		}
		//APP用户连接放行
		if( uri.contains( "/ws/" ) ){
			return true;
		}
		//Data服务器请求推送服务，放行
//		if( uri.contains( "/****" ) ){
//			return true;
//		}
		
		//APP请求访问服务器，拦截在线过滤
		String userName = request.getParameter("userName");
		String token = request.getParameter("token");
		if (userName != null && !userName.trim().equals("") && token != null && !token.trim().equals("")) {
			// 判断用户是否在线
			boolean flag = OnlineManage.isOnlined(userName);
			if (true == flag) {
				if (true == OnlineManage.getOnlineUser(userName).getToken().equals(token)) {
					return true;
				}
			}
		}
		PrintWriter out = ResponseUtil.responseJSON(response);
		Map<String, String> map = new HashMap<String, String>();
		map.put("status", "error");
		map.put("msg", "用户未登录");
		out.write(new ObjectMapper().writeValueAsString(map));
		out.flush();
		out.close();
		return false;
	}

}
